<?php

namespace App\Http\Controllers\Api;

use App\Cinema;
use App\FilmTicket;
use App\Option;
use App\Order;
use App\OrderFilmTicket;
use App\OrderOriginal;
use App\Screen;
use App\Seats;
use App\Session;
use App\SessionSeat;
use App\ShowtimeSchedule;
use App\TicketRefundRecognition;
use Carbon\Carbon;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class OrderController extends BaseController
{
    //

    public $user;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->user = $this->is_login($request);
    }


    /**
     * @param Request $request
     * 前台售票选择影片
     */
    public function select_film(Request $request){

        if (!$this->user['data']->can('buy_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];

        if (!$business_date = trim($request->input('business_date'))){
            return error('营业日缺失');
        }
        $next_date = Carbon::parse($business_date)->addDay(1);

        $data = ShowtimeSchedule::select(DB::raw('name,count(project_ids) as count,project_ids'))
            ->whereBetween('start_time',[$business_date,$next_date])
            ->where('status','=',1)
            ->where('end_time','>',date('Y-m-d H:i:s'))
            ->where('cinema_code','=',$cinema_code)
            ->groupBy(['project_ids','name'])->get();
        foreach ($data as $key=>$val){
            $data[$key]['ticket_list'] = ShowtimeSchedule::where('name','=',$val->name)
                ->whereBetween('start_time',[$business_date,$next_date])
                ->where('end_time','>',date('Y-m-d H:i:s'))
                ->where('status','=',1)
                ->where('cinema_code','=',$cinema_code)
                ->orderBy('start_time')
                ->get();
        }

        return success($data,'查询成功');
    }


    //本地下订单
    public function local_lock_seat(Request $request){

        if (!$this->user['data']->can('buy_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if(!$showtime_schedule_code = trim($request->input('showtime_schedule_code'))){
            return error('放映计划缺失');
        }

        if(!$seats = trim($request->input('seats'))){
            return error('座位编码信息缺失');
        }

        $showtime_schedul = ShowtimeSchedule::where(['cinema_code'=>$cinema_code,'code'=>$showtime_schedule_code,'status'=>1])->first();
        if (!$showtime_schedul){
            return error('放映计划不存在');

        }

        $end_time = Carbon::parse($showtime_schedul->end_time);
        $now_time = Carbon::now();
        if ($now_time->gt($end_time)){
            return error('该场次已结束放映');
        }

        if ($showtime_schedul->status!=1){
            return error('该放映计划已删除或已暂停发售');
        }

        $seats = explode(',',$seats);

        $count = count($seats);

        $res_count = FilmTicket::whereIn('seat_code',$seats)->where(['status'=>1,'showtime_schedule_code'=>$showtime_schedule_code])->lockForUpdate()->count();

        if ($count!=$res_count) {
            return error('下订单失败,影票编码错误或已售');
        }

        \DB::beginTransaction();
        try{
            //查询对应的影票
            $film_ticket_list = FilmTicket::whereIn('seat_code', $seats)->where(['status' => 1, 'showtime_schedule_code' => $showtime_schedule_code])->get();
            //修改影票库中影票状态为已锁定
            $res_film_tickets = FilmTicket::whereIn('seat_code', $seats)->where(['status' => 1, 'showtime_schedule_code' => $showtime_schedule_code])->update(['status'=>2]);

            //订单表添加订单
            $order = new Order();
            $order->code = get_order_code();
            $order->auto_unlock_datetime = Carbon::now()->addMinute(5);
            $order->cinema_code = $cinema_code;
            $order->cinema_name = $showtime_schedul->cinema_name;
            $order->cinema_status = $showtime_schedul->cinema_status;
            $order->screen_code = $showtime_schedul->screen_code;
            $order->screen_name = $showtime_schedul->screen_name;
            $order->showtime_schedule_code = $showtime_schedule_code;
            $order->showtime_schedule_name = $showtime_schedul->name;
            $order->start_time = $showtime_schedul->start_time;
            $order->end_time = $showtime_schedul->end_time;
            $order->playthrough_flag = $showtime_schedul->playthrough_flag;
            $order->films = $showtime_schedul->films;
            $order->seat_by_number = $showtime_schedul->seat_by_number;
            $order->channel_id = $this->user['data']['id'];
            $order->status = 1;
            $order->last_modify = Carbon::now();
            $res_order = $order->save();

            $order_film_ticket_arr = [];
            //循环座位信息，造订单影票信息结构
            foreach ($film_ticket_list as $val) {
                $order_film_ticket = [];
                $order_film_ticket['order_code'] = $order->code;
                $order_film_ticket['seat_code'] = $val['seat_code'];
                $order_film_ticket['cinema_code'] = $val['cinema_code'];
                $order_film_ticket['row_num'] = $val['row_num'];
                $order_film_ticket['column_num'] = $val['column_num'];
                $order_film_ticket['x_coord'] = $val['x_coord'];
                $order_film_ticket['y_coord'] = $val['y_coord'];
                $order_film_ticket['group_code'] = $val['group_code'];
                $order_film_ticket['film_ticket_code'] = $val['code'];
                $order_film_ticket['service'] = 0;
                $order_film_ticket['lowest_price'] = $val['lowest_price'];
                $order_film_ticket['from'] = 1;
                $order_film_ticket_arr[] = $order_film_ticket;
            }

            $res_order_film_ticket = \DB::table('order_film_tickets')->insert($order_film_ticket_arr);
            if ($res_film_tickets && $res_order && $res_order_film_ticket) {
                \DB::commit();
                $order['tickets'] = OrderFilmTicket::where('order_code','=',$order->code)->select();
                logs($this->user,json_encode(['type'=>'order','msg'=>'下订单'.$order->code.'成功','info'=>$order]));
                return success($order, '下订单成功');
            }

        }catch (\Exception $e){
            \DB::rollBack();
            $order['tickets'] = OrderFilmTicket::where('order_code','=',$order->code)->select();
            logs($this->user,json_encode(['type'=>'order','msg'=>'下订单'.$order->code.'失败','info'=>$order]));
            return error('下订单失败');
        }


    }

    /**
     * @param Request $request
     * @return array
     * 本地解锁票
     */
    public function local_release_seat(Request $request){

        if (!$this->user['data']->can('buy_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];

        if(!$order_code = trim($request->input('order_code'))){
            return error('订单号缺失');
        }

        $order = Order::where(['code'=>$order_code,'status'=>1,'cinema_code'=>$cinema_code])->first();
        if (!$order){
            return error('不存在锁票订单或订单已失效、支付');
        }

        $seat_codes = OrderFilmTicket::where(['order_code'=>$order->code,'status'=>1])->pluck('seat_code');

        \DB::beginTransaction();
        try{
            $order->status = 5;
            $res_order = $order->save();

            $update_order_film_ticket = OrderFilmTicket::where(['order_code'=>$order->code,'status'=>1])->update(['status'=>2]);

            $update_film_ticket = FilmTicket::where(['showtime_schedule_code'=>$order->showtime_schedule_code])->whereIn('seat_code',$seat_codes)->update(['status'=>1]);

            if ($res_order&&$update_film_ticket&&$update_order_film_ticket){
                \DB::commit();
                $order['tickets'] = OrderFilmTicket::where('order_code','=',$order->code)->whereIn('seat_code',$seat_codes)->select();
                logs($this->user,json_encode(['type'=>'order','msg'=>'解锁订单'.$order->code.'成功','info'=>$order]));
                return success('','解锁成功');
            }
        }catch (\Exception $e){
            \DB::rollBack();
            $order['tickets'] = OrderFilmTicket::where('order_code','=',$order->code)->whereIn('seat_code',$seat_codes)->select();
            logs($this->user,json_encode(['type'=>'order','msg'=>'解锁订单'.$order->code.'失败','info'=>$order]));
            return error('解锁失败');
        }

    }


    /**
     * @param Request $request
     * 本地支付
     */
    public function local_submit_order(Request $request){

        if (!$this->user['data']->can('buy_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if(!$order_code = trim($request->input('order_code'))){
            return error('订单编码缺失');
        }
        if(!$seats = trim($request->input('seats'))){
            return error('座位信息缺失');
        }

        //查询订单信息
        $order = Order::where(['code'=>$order_code,'status'=>1,'cinema_code'=>$cinema_code])->first();
        if (!$order){
            return error('订单号不存在或已支付打印');
        }

        if ($order->status==5){
            return error('订单已失效');
        }
        $seats = json_decode($seats,true);
        $seat_codes = array_keys($seats);
        $order_film_ticket_list = OrderFilmTicket::where(['orders.status'=>1,'order_code'=>$order_code])
            ->join('orders','orders.code','=','order_film_tickets.order_code')
            ->select("order_film_tickets.*","orders.status as order_status","orders.films as films","orders.screen_code as screen_code","orders.showtime_schedule_code as showtime_schedule_code",'orders.start_time as start_time')
            ->get();
        if ($order_film_ticket_list->count()!=count($seats)){
            return error('座位信息与订单中座位信息不对应');
        }

        $showtime_schedule_info = ShowtimeSchedule::where(['status'=>1,'code'=>$order->showtime_schedule_code])->first();

        if (!$showtime_schedule_info){
            return error('放映计划不存在，或已失效');
        }

        $session_info = Session::where(['showtime_schedule_code'=>$order->showtime_schedule_code])->get()->toArray();






        //造原始数据表数据
        $order_original = [];
        $order_original_list = FilmTicket::where(['film_tickets.showtime_schedule_code'=>$order->showtime_schedule_code])->whereIn('seat_code',$seat_codes)
            ->join('sessions','sessions.showtime_schedule_code','=','film_tickets.showtime_schedule_code')
            ->select('film_tickets.*','sessions.playthrough_flag','sessions.playthrough_price','sessions.code as session_code','sessions.start_time as session_datetime','sessions.film_code as film_code')
            ->orderBy('id')
            ->get();

        $ticket_codes = [];
        $new_ticket_codes = [];

        foreach ($order_original_list as $val){
            $insert_order_original = [];
            $insert_order_original['cinema_code'] = $cinema_code;
            $insert_order_original['code'] = get_order_original_code();
            $insert_order_original['order_code'] = $order_code;
            $insert_order_original['cinema_status'] = $val['cinema_status'];
            $insert_order_original['business_date'] = $val['business_date'];
            $insert_order_original['screen_code'] = $val['screen_code'];
            $insert_order_original['film_code'] = $val['film_code'];
            $insert_order_original['session_code'] = $val['session_code'];
            $insert_order_original['showtime_schedule_code'] = $val['showtime_schedule_code'];
            $insert_order_original['session_datetime'] = date('Y-m-d H:i:s',$val['session_datetime']);
            $session_datetime = Carbon::parse($insert_order_original['session_datetime']);
            $tomorrow = Carbon::tomorrow();
            $insert_order_original['operation'] = $session_datetime->lte($tomorrow)?1:3;
            $insert_order_original['film_ticket_code'] = $val['code'];
            $insert_order_original['seat_code'] = $val['seat_code'];
            if ($val['playthrough_flag']==1){
                $insert_order_original['price'] = $val['playthrough_price'];
            }else{
                $insert_order_original['price'] = $seats[$val['seat_code']];
            }
            $insert_order_original['service'] = 0;
            $insert_order_original['online_sale'] = 1;
            $insert_order_original['channel_id'] = $this->user['data']['id'];
            $insert_order_original['date_time'] = Carbon::now();
            $insert_order_original['flag'] = 1;
            $ticket_codes[] = $val['code'];
            $new_ticket_codes[$val['code']] = $insert_order_original['code'];
            $order_original[]=$insert_order_original;
        }




        $ticketdata = [];

        foreach ($order_film_ticket_list as $val){
            $info = [];
            $info['ticket_code'] = $new_ticket_codes[$val['film_ticket_code']];
            $info['screen_code'] = $val['screen_code'];
            $info['film_code'] = json_decode($val['films'],true)[0]['film_code'];
            $info['session_code'] = $session_info[0]['code'];
            $info['session_datetime'] = str_replace(' ','T',$val['start_time']);
            $info['seat_code'] = $val['seat_code'];
            $info['price'] = $seats[$val['seat_code']];
            $info['service'] = $val['service'];
            $info['cinema_code'] = $val['cinema_code'];
            $ticketdata[] = $info;
        }

        // return $info;

        $str = http_build_query([
            'ticketdata'=>json_encode($ticketdata),
            'cinema_code'=>$cinema_code
        ]);

        $res = curl($_ENV['SERVER_G'].'/ticket_sign',$str,true);

        $res = json_decode($res,true);

        $film_ticket_informations = '';

        if ($res['success']){
            $film_ticket_informations = $res['result']['ticket_sign'];
        }else{
            return error('获取电影票信息码失败');
        }


        //组织订单影票信息，更新订单影票状态
        $order_film_tickets = [];
        foreach ($order_film_ticket_list as $val){
            //实际售卖票与影片最低票价作比较。低于最低票价不可售
            if ($seats[$val['seat_code']]<$showtime_schedule_info['lowest_price']){
                return error('低于影片最低价不可售');
            }
            $film_ticket_order = [];
            $film_ticket_order['id'] = $val['id'];
            $film_ticket_order['price'] = $seats[$val['seat_code']];
            $film_ticket_order['pay_status'] = 1;
            $film_ticket_order['pay_time'] = Carbon::now();
            $film_ticket_order['service'] = 0;
            $film_ticket_order['film_ticket_information'] = $film_ticket_informations[$new_ticket_codes[$val['film_ticket_code']]];
//            $film_ticket_order['film_ticket_information'] = get_film_ticket_information();
            $order_film_tickets[] = $film_ticket_order;
        }




        DB::beginTransaction();
        try{
            //修改订单状态为已出票
            $order->status = 2;
            $order->print_no = get_print_no();
            $order->verify_code = get_verify_code();
            $order->last_modify = date("Y-m-d H:i:s");
            $res_order = $order->save();
            //根据id更新订单影票信息

            $res_order_film_ticket = updateBatch('order_film_tickets',$order_film_tickets);

            $res_film_ticket_status = FilmTicket::whereIn('code',$ticket_codes)->update(['status'=>3]);
            //添加订单明细表记录
            $res_order_original = \DB::table('order_originals')->insert($order_original);
            if ($res_film_ticket_status&&$res_order&&$res_order_film_ticket&&$res_order_original){
                \DB::commit();
                $order['tickets'] = OrderFilmTicket::where('order_code','=',$order_code)->whereIn('seat_code',$seat_codes)->select();
                logs($this->user,json_encode(['type'=>'order','msg'=>'支付订单'.$order_code.'成功','info'=>$order]));
                return success(json_encode($order),'支付成功');
            }
        }catch (\Exception $e){
            \DB::rollBack();
            $order['tickets'] = OrderFilmTicket::where('order_code','=',$order_code)->whereIn('seat_code',$seat_codes)->select();
            logs($this->user,json_encode(['type'=>'order','msg'=>'支付订单'.$order_code.'失败','info'=>$order]));
            return error('支付失败');
        }


    }

    /**
     * @param Request $request
     * 验证订单是否可打印
     */
    public function verify_print_status(Request $request){
        if (!$this->user['data']->can(['buy_ticket','sale_printer_ticket'])){
            return error('NoPermission');
        }
        $cinema_code = $this->user['data']['cinema_code'];
        if(!$order_code = trim($request->order_code)){
            return error('订单编码缺失');
        }
        $order_info = Order::where(['code'=>$order_code,'cinema_code'=>$cinema_code])->first();

        $seat_group = Option::where('options_type','=','group_code')->pluck('options_value','options_key');

        if (in_array($order_info['status'],[2,3])){
            $order_list = OrderFilmTicket::where(['order_code'=>$order_code,'status'=>1,'pay_status'=>1,'refund_status'=>2])
                ->get();
            $ticket_print_info = [];
            foreach ($order_list as $val){
                $ticket_info = [];
                $ticket_info['cinema_name'] = $order_info['cinema_name'];
                $ticket_info['hall_name'] = $order_info['screen_name'];
                $ticket_info['show_time'] = Carbon::parse($order_info['start_time'])->format('H:i:s');
                $ticket_info['movie_name'] = $order_info['showtime_schedule_name'];
                $seat = $order_info['seat_by_number']==1?$val['row_num'].'排'.$val['column_num'].'座':$val['row_num'].'排'.$val['column_num'].'座(不对号入座)';
                $ticket_info['seat'] = $seat;
                $ticket_info['price'] = (int)($val['price']);
                $ticket_info['ticket_information'] = $val['film_ticket_information'];
                $ticket_info['show_date'] = Carbon::parse($order_info['start_time'])->format('Y-m-d');
                $ticket_info['film_ticket_code'] = OrderOriginal::where('film_ticket_code','=',$val['film_ticket_code'])->orderBy('id','DESC')->value('code');
                $ticket_info['date_time'] = $val['pay_time'];
                $ticket_info['seat_type'] =$seat_group[$val['group_code']];
                $ticket_info['channel'] = User::where('id','=',$order_info['channel_id'])->value('name');
                $ticket_info['service'] = (int)$val['service'];
                $ticket_info['online_type'] = $order_info['from']==1?'否':'是';
                $ticket_print_info[] = $ticket_info;
            }

            return success($ticket_print_info,'可打印');
        }else{
            return error('订单不可打印');
        }
    }

    /**
     * @param Request $request
     * 验证网售订单是否可打印
     */
    public function print_order_info(Request $request){
        if (!$this->user['data']->can('sale_printer_ticket')){
            return error('NoPermission');
        }
        $cinema_code = $this->user['data']['cinema_code'];
        if(!$print_no = trim($request->print_no)){
            return error('出票码');
        }
        if(!$verify_code = trim($request->verify_code)){
            return error('出票验证码');
        }
        $order_info = Order::where(['print_no'=>$print_no,'orders.cinema_code'=>$cinema_code,'verify_code'=>$verify_code])
            ->join('users','users.id','=','orders.channel_id')
            ->select('orders.*','users.name as channel_name')
            ->first();
        if ($order_info&&in_array($order_info['status'],[2,3])){
            $order_list = OrderFilmTicket::where(['order_code'=>$order_info->code,'status'=>1,'pay_status'=>1,'refund_status'=>2])
                ->get();
            if (count($order_list)==0){
                return error('订单中不存在可打印的票');
            }
            return success(['order_info'=>$order_info,'tickets'=>$order_list],'查询成功');
        }else{
            return error('订单不可打印');
        }

    }


    /**
     * @param Request $request
     * @return array
     * 修改订单打印状态
     */
    public function set_order_print_status(Request $request){
        if (!$this->user['data']->can(['buy_ticket','sale_printer_ticket'])){
            return error('NoPermission');
        }
        $cinema_code = $this->user['data']['cinema_code'];
        if(!$order_code = trim($request->order_code)){
            return error('订单编码缺失');
        }
        $order_info = Order::where(['code'=>$order_code,'cinema_code'=>$cinema_code])->first();
        if (!$order_info){
            return error('订单不存在');
        }
        DB::beginTransaction();
        try{
            $order_info->status = 3;
            $res_order = $order_info->save();
            $seat_codes = OrderFilmTicket::where(['order_code'=>$order_code,'status'=>1,'pay_status'=>1,'refund_status'=>2])->pluck('seat_code');

            $res_order_film_ticket = OrderFilmTicket::where(['order_code'=>$order_code,'status'=>1,'pay_status'=>1,'refund_status'=>2])->update(['print_status'=>1]);
            if ($res_order&&$res_order_film_ticket){
                DB::commit();
                $order_info['tickets'] = OrderFilmTicket::where('order_code','=',$order_code)->whereIn('seat_code',$seat_codes)->select();
                logs($this->user,json_encode(['type'=>'order','msg'=>'订单'.$order_code.'已打印','info'=>$order_info]));
                return success('','订单已打印');
            }
        }catch (\Exception $e){
            DB::rollBack();
            $order_info['tickets'] = OrderFilmTicket::where('order_code','=',$order_code)->whereIn('seat_code',$seat_codes)->select();
            logs($this->user,json_encode(['type'=>'order','msg'=>'修改订单'.$order_code.'打印状态失败','info'=>$order_info]));
            return error('修改订单打印状态失败');
        }
    }



    /**
     * @param Request $request
     * 本地退票通过电影票编码
     */
    public function local_refund_ticket_by_code(Request $request){
        //order状态为4代表已退票
        if (!$this->user['data']->can(['sale_refund_ticket','admin_refund_ticket'])){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$film_ticket_code = $request->film_ticket_code){
            return error('电影票编码缺失');
        }


        $film_ticket_code = explode(',',$film_ticket_code);
        $film_ticket_code = OrderOriginal::whereIn('code',$film_ticket_code)->pluck('film_ticket_code');

        \DB::beginTransaction();
        try{

            $refund_tickets = OrderFilmTicket::where(['order_film_tickets.cinema_code'=>$cinema_code,'order_film_tickets.status'=>1,'pay_status'=>1,'refund_status'=>2])
                ->whereIn('film_ticket_code',$film_ticket_code)->lockForUpdate()->get();


            if (count($refund_tickets)!=count($film_ticket_code)){
                return error('存在不可退影票');
            }

            $order_codes = [];
            foreach ($refund_tickets as $val){
                $order_codes[] = $val->order_code;
            }

            $order_codes = array_unique($order_codes);
            if (count($order_codes)>1){
                return error('订单不同不可同时退票');
            }

            $order_code = $order_codes[0];


            $film_ticket_count = FilmTicket::whereIn('code',$film_ticket_code)->whereIn('status',[2,3])->count();


            if ($film_ticket_count!=count($film_ticket_code)){
                return error('存在不可退影票');
            }

            $order_tickets = [];
            $tickets = [];
            $price = 0;
            foreach ($film_ticket_code as $val){
                $order_original = OrderOriginal::where(['order_code'=>$order_code,'film_ticket_code'=>$val])->orderBy('date_time','desc')->first();
                if (!in_array($order_original->operation,[1,3,4])){
                    return error('存在不可退电影票');
                }
                $order_originals = OrderOriginal::where(['order_code'=>$order_code,'film_ticket_code'=>$val])->whereIn('operation',[1,3,4])->get()->toArray();
                $price = OrderOriginal::where(['order_code'=>$order_code,'film_ticket_code'=>$val])->whereIn('operation',[1,3,4])->sum('price');
                $tickets[] = [$val=>(int)$price];
                $order_tickets = array_merge($order_originals,$order_tickets);
            }


            $remark = $request->remark;
            $code = get_order_original_code();

            $showtime_schedule_code = Order::where(['code'=>$order_code])->value('showtime_schedule_code');
            $showtime_schedules = ShowtimeSchedule::where('code','=',$showtime_schedule_code)->first();
            $end_time = Carbon::parse($showtime_schedules->end_time);
            $now_time = Carbon::now();
            if ($now_time->lt($end_time)){
                
                foreach ($order_tickets as $key=>$val){
                    unset($order_tickets[$key]['id']);
                    $order_tickets[$key]['operation'] = 2;
                    $order_tickets[$key]['date_time'] = Carbon::now();
                    $order_tickets[$key]['flag'] = 1;
                    $order_tickets[$key]['is_counted'] = 0;
                    $order_tickets[$key]['channel_id'] = $this->user['data']['id'];
                    $order_tickets[$key]['remark'] = $remark;
                    $order_tickets[$key]['code'] = $code;
                }
                $res_order_original = \DB::table('order_originals')->insert($order_tickets);            

            }

            $ticket_refund_recognitions = new TicketRefundRecognition();
            $ticket_refund_recognitions->code = unique_rand(16);
            $ticket_refund_recognitions->order_code = $order_code;
            $ticket_refund_recognitions->cinema_code = $cinema_code;
            $ticket_refund_recognitions->business_date = $showtime_schedules->business_date;
            $ticket_refund_recognitions->screen_code = $showtime_schedules->screen_code;
            $ticket_refund_recognitions->film_code = explode(',',$showtime_schedules->film_codes)[1];
            $ticket_refund_recognitions->film_name = $showtime_schedules->name;
            $ticket_refund_recognitions->session_code = $showtime_schedules->code;
            $ticket_refund_recognitions->session_datetime = $showtime_schedules->start_time;
            $ticket_refund_recognitions->operation = 2;
            $ticket_refund_recognitions->tickets = json_encode($tickets);
            $ticket_refund_recognitions->price = $price;
            $ticket_refund_recognitions->online_sale = 1;
            $ticket_refund_recognitions->count = $film_ticket_count;
            $ticket_refund_recognitions->channel_id = $this->user['data']['id'];
            $ticket_refund_recognitions->channel_name = $this->user['data']['name'];
            $ticket_refund_recognitions->flag = $now_time->lt($end_time)?1:2;
            $ticket_refund_recognitions->status = $now_time->lt($end_time)?2:0;
            $ticket_refund_recognitions->date_time = Carbon::now();
            $ticket_refund_recognitions->is_migrationed = $now_time->lt($end_time)?1:2;


            if ($now_time->lt($end_time)) {
                $res_order_film_ticket = OrderFilmTicket::whereIn('film_ticket_code', $film_ticket_code)->update(['refund_status' => 1, 'refund_time' => Carbon::now()]);
                $res_film_ticket = FilmTicket::whereIn('code', $film_ticket_code)->update(['status' => 1]);
            }
            $res_ticket_refund_recognition = $ticket_refund_recognitions->save();
            if ($res_ticket_refund_recognition){
                \DB::commit();
                if($now_time->lt($end_time)){
                    logs($this->user,'本地退电影票'.json_encode($film_ticket_code).'成功');
                    return success('','退票成功');
                }else{
                    logs($this->user,'本地退电影票'.json_encode($film_ticket_code).'受理中');
                    return success('','已接受退票处理');
                }
            }
        }catch (\Exception $e){
            \DB::rollBack();
            logs($this->user,'本地退电影票'.json_encode($film_ticket_code).'失败');
            return error('退票失败');
        }

    }

    /**
     * @param Request $request
     * @return array
     * 查看退票列表
     */
    public function refund_ticket_list(Request $request){

        if (!$this->user['data']->can('admin_refund_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        $showtime_start_time=trim($request->input('start_session_datetime'));
        $showtime_end_time = trim($request->input('end_session_datetime'));
        $start_date_time = trim($request->start_date_time);
        $end_date_time = trim($request->end_date_time);
        $channel_name=trim($request->channel_name);
        $refund_list = \DB::table('ticket_refund_recognitions')->orderBy('date_time','desc');
        $channel_name&&$refund_list->where('channel_name','like','%'.$channel_name.'%');
        $showtime_start_time&&$showtime_end_time&&$refund_list->whereBetween('date_time',[$showtime_start_time,$showtime_end_time]);
        $start_date_time&&$end_date_time&&$refund_list->whereBetween('date_time',[$start_date_time,$end_date_time]);
        // $refund_list->orderBy('date_time','DESC')
        $data = $refund_list->where(['operation'=>2,'cinema_code'=>$cinema_code])->paginate(15);
        return success($data,'查询成功');
    }

    /**
     * @param Request $request
     * 本地验票
     */
    public function check_ticket(Request $request){

        if (!$this->user['data']->can(['check_ticket','admin_check_ticket'])){
            return error('NoPermission');
        }

        $film_ticket_information = $request->input('film_ticket_information');
        $film_ticket_code = $request->input('film_ticket_code');

        if (!($film_ticket_information||$film_ticket_code)){
            return error('验票码缺失');
        }

        $film_ticket_code&&$film_ticket_code = OrderOriginal::where('code','=',$film_ticket_code)->value('film_ticket_code');


        $order_info = DB::table('order_film_tickets')
            ->join('orders','orders.code','=','order_film_tickets.order_code')
            ->join('users','users.id','=','orders.channel_id')
            ->where('order_film_tickets.pay_status','=',1)
            ->where('order_film_tickets.refund_status','=',2);

        $film_ticket_information&&$order_info->where(['film_ticket_information'=>$film_ticket_information]);
        $film_ticket_code&&$order_info->where('film_ticket_code','=',$film_ticket_code);

        $order_info = $order_info->select('orders.*'
            ,'users.name as channel_name'
            ,'users.name as channel_name'
            ,'order_film_tickets.row_num as row_num'
            ,'order_film_tickets.column_num as column_num'
            ,'order_film_tickets.price as price'
            ,'order_film_tickets.film_ticket_code as film_ticket_code'
            ,'order_film_tickets.service as service'
            ,'order_film_tickets.pay_status as pay_status'
            ,'order_film_tickets.print_status as print_status'
            ,'order_film_tickets.refund_status as refund_status')
        ->first();


        if (!$order_info){
            return error('电影票不存在');
        }

        $order_info->film_ticket_code = OrderOriginal::where('film_ticket_code','=',$order_info->film_ticket_code)->orderBy('id','DESC')->value('code');


        $order_info->status = $order_info->refund_status==1?'已退票':$order_info->print_status==1?'已取票':'已支付';

        return success($order_info,'查询成功');

    }

    /**
     * @param Request $request
     * 补登
     */
    public function board(Request $request){

        if (!$this->user['data']->can('admin_bound_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];

        if (!$showtime_schedule_code = trim($request->input('showtime_schedule_code'))){
            return error('放映计划编码缺失');
        }
        if (!$price = trim($request->input('price'))){
            return error('单张影票价格缺失');
        }
        if (!$count = trim($request->input('count'))){
            return error('补登总数缺失');
        }
        $remark = $request->remark;

        $showtime_schedule_info = ShowtimeSchedule::where(['code'=>$showtime_schedule_code])->first();
        if (!$showtime_schedule_info){
            return error('放映场次不存在');
        }
        if ($showtime_schedule_info->status!=1){
            return error('放映场次已删除或已被暂停');
        }
        $end_time = Carbon::parse($showtime_schedule_info->end_time);
        $now_time = Carbon::now();
        if ($end_time->gt($now_time)){
            return error('放映结束前可以正常售票');
        }

        \DB::beginTransaction();
        try{

            $film_ticket_code_list = FilmTicket::where(['showtime_schedule_code'=>$showtime_schedule_code,'status'=>1])->limit($count)->lockForUpdate()->pluck('code');
            if ($film_ticket_code_list->count()<$count){
                return error('剩余票不足');
            }



            $tickets = [];
            foreach ($film_ticket_code_list as $val){
                $tickets[][$val]=(int)$price;
            }

            $film_ticket_list = FilmTicket::where(['film_tickets.showtime_schedule_code'=>$showtime_schedule_code,'film_tickets.status'=>1])
                ->whereIn('film_tickets.code',$film_ticket_code_list)
                ->join('sessions','sessions.showtime_schedule_code','=','film_tickets.showtime_schedule_code')
                ->select('sessions.code as session_code'
                    ,'sessions.film_code as film_code'
                    ,'sessions.playthrough_flag as playthrough_flag'
                    ,'sessions.playthrough_price as playthrough_price'
                    ,'film_tickets.*'
                )->get();

            $ticket_list = FilmTicket::where(['film_tickets.showtime_schedule_code'=>$showtime_schedule_code,'film_tickets.status'=>1])
                ->whereIn('film_tickets.code',$film_ticket_code_list)
                ->get();

            $has_seven_days = $now_time->gt(Carbon::parse($end_time)->addDay(7));

            //订单表添加订单
            $order = new Order();
            $order->code = get_order_code();
            $order->auto_unlock_datetime = Carbon::now()->addYears(20);
            $order->cinema_code = $cinema_code;
            $order->cinema_name = $showtime_schedule_info->cinema_name;
            $order->cinema_status = $showtime_schedule_info->cinema_status;
            $order->screen_code = $showtime_schedule_info->screen_code;
            $order->screen_name = $showtime_schedule_info->screen_name;
            $order->showtime_schedule_code = $showtime_schedule_code;
            $order->showtime_schedule_name = $showtime_schedule_info->name;
            $order->start_time = $showtime_schedule_info->start_time;
            $order->end_time = $showtime_schedule_info->end_time;
            $order->playthrough_flag = $showtime_schedule_info->playthrough_flag;
            $order->films = $showtime_schedule_info->films;
            $order->seat_by_number = $showtime_schedule_info->seat_by_number;
            $order->channel_id = $this->user['data']['id'];
            $order->status = $has_seven_days?1:2;
            $order->last_modify = Carbon::now();
            $res_order = $order->save();

            $order_film_ticket_arr = [];
            //循环座位信息，造订单影票信息结构
            foreach ($ticket_list as $val) {
                $order_film_ticket = [];
                $order_film_ticket['order_code'] = $order->code;
                $order_film_ticket['seat_code'] = $val['seat_code'];
                $order_film_ticket['cinema_code'] = $val['cinema_code'];
                $order_film_ticket['row_num'] = $val['row_num'];
                $order_film_ticket['column_num'] = $val['column_num'];
                $order_film_ticket['x_coord'] = $val['x_coord'];
                $order_film_ticket['y_coord'] = $val['y_coord'];
                $order_film_ticket['group_code'] = $val['group_code'];
                $order_film_ticket['film_ticket_code'] = $val['code'];
                $order_film_ticket['service'] = 0;
                $order_film_ticket['price'] = $price;
                $order_film_ticket['lowest_price'] = $val['lowest_price'];
                $order_film_ticket['pay_status'] = $has_seven_days?2:1;
                $order_film_ticket['pay_time'] = $has_seven_days?null:$now_time;
                $order_film_ticket['from'] = 1;
                $order_film_ticket_arr[] = $order_film_ticket;
            }

            $res_order_film_ticket = \DB::table('order_film_tickets')->insert($order_film_ticket_arr);


            $order_code = $order->code;
            $ticket_refund_recognitions = new TicketRefundRecognition();
            $ticket_refund_recognitions->code = unique_rand(16);
            $ticket_refund_recognitions->order_code = $order_code;
            $ticket_refund_recognitions->cinema_code = $cinema_code;
            $ticket_refund_recognitions->tickets = json_encode($tickets);
            $ticket_refund_recognitions->business_date = $showtime_schedule_info->business_date;
            $ticket_refund_recognitions->screen_code = $showtime_schedule_info->screen_code;
            $ticket_refund_recognitions->film_code = explode(',',$showtime_schedule_info->film_codes)[1];
            $ticket_refund_recognitions->film_name = $showtime_schedule_info->name;
            $ticket_refund_recognitions->session_code = $showtime_schedule_info->code;
            $ticket_refund_recognitions->session_datetime = $showtime_schedule_info->start_time;
            $ticket_refund_recognitions->operation = 4;
            $ticket_refund_recognitions->price = $price*$count;
            $ticket_refund_recognitions->online_sale = 1;
            $ticket_refund_recognitions->count = $count;
            $ticket_refund_recognitions->channel_id = $this->user['data']['id'];
            $ticket_refund_recognitions->channel_name = $this->user['data']['name'];
            $ticket_refund_recognitions->flag = $now_time->lt(Carbon::parse($end_time)->addDay(7))?1:2;
            $ticket_refund_recognitions->status = $now_time->lt(Carbon::parse($end_time)->addDay(7))?2:0;
            $ticket_refund_recognitions->date_time = Carbon::now();
            $ticket_refund_recognitions->is_migrationed = $now_time->lt(Carbon::parse($end_time)->addDay(7))?1:2;


            if (!$has_seven_days) {
                $data = [];
                foreach ($film_ticket_list as $val) {
                    $order_original = [];
                    $order_original['code'] =  get_order_original_code();
                    $order_original['order_code'] = $order_code;
                    $order_original['cinema_code'] = $cinema_code;
                    $order_original['cinema_status'] = $val['cinema_status'];
                    $order_original['business_date'] = $val['business_date'];
                    $order_original['screen_code'] = $val['screen_code'];
                    $order_original['film_code'] = $val['film_code'];
                    $order_original['session_code'] = $val['session_code'];
                    $order_original['showtime_schedule_code'] = $val['showtime_schedule_code'];
                    $order_original['session_datetime'] = $val['start_time'];
                    $order_original['operation'] = 4;
                    $order_original['film_ticket_code'] = $val['code'];
                    $order_original['seat_code'] = $val['seat_code'];
                    if ($val['playthrough_flag']==1){
                        $order_original['price'] = $val['playthrough_price'];
                    }else{
                        $order_original['price'] = $price;
                    }
                    $order_original['service'] = 0;
                    $order_original['online_sale'] = 1;
                    $order_original['date_time'] = Carbon::now();
                    $order_original['flag'] = 1;
                    $order_original['channel_id'] = $this->user['data']['id'];
                    $order_original['remark'] = $remark;
                    $data[] = $order_original;
                    $film_ticket_codes[] = $val['code'];
                }
                \DB::table('order_originals')->insert($data);
                $res_film_tickets = FilmTicket::whereIn('code',$film_ticket_code_list)->update(['status'=>3]);
            }else{
                $res_film_tickets = FilmTicket::whereIn('code',$film_ticket_code_list)->update(['status'=>2]);
            }
            $res_ticket_refund_recognitions = $ticket_refund_recognitions->save();
            if ($res_film_tickets&&$res_ticket_refund_recognitions&&$res_order_film_ticket){
                \DB::commit();
                if( $has_seven_days){
                    logs($this->user,json_encode(['type'=>'board','msg'=>Carbon::now().'已接受补登处理:'.$order_code,'info'=>['count'=>$count,'price'=>$price,'name'=>$showtime_schedule_info->name,'business_date'=>$showtime_schedule_info->business_date,'session_datetime'=>$showtime_schedule_info->start_time]]));
                    return success('','已接受补登处理');
                }else{
                    logs($this->user,json_encode(['type'=>'board','msg'=>Carbon::now().'补登成功:'.$order_code,'info'=>['count'=>$count,'price'=>$price,'name'=>$showtime_schedule_info->name,'business_date'=>$showtime_schedule_info->business_date,'session_datetime'=>$showtime_schedule_info->start_time]]));
                    return success('','补登成功');
                }
            }
        }catch (\Exception $e){
            \DB::rollBack();
            logs($this->user,json_encode(['type'=>'board','msg'=>Carbon::now().'补登失败:','info'=>['count'=>$count,'price'=>$price,'name'=>$showtime_schedule_info->name,'business_date'=>$showtime_schedule_info->business_date,'session_datetime'=>$showtime_schedule_info->start_time]]));
            return error('补登失败');
        }

    }

    /**
     * @param Request $request
     * @return array
     * 查看补登列表
     */
    public function get_board_list(Request $request){

        if (!$this->user['data']->can('admin_bound_ticket')){
            return error('NoPermission');
        }

        if (!$this->user['data']->can('admin_refund_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        $showtime_start_time=trim($request->input('start_session_datetime'));
        $showtime_end_time = trim($request->input('end_session_datetime'));
        $start_date_time = trim($request->start_date_time);
        $end_date_time = trim($request->end_date_time);
        $channel_name=trim($request->channel_name);
        $refund_list = \DB::table('ticket_refund_recognitions')->orderBy('date_time','desc');
        $channel_name&&$refund_list->where('channel_name','like','%'.$channel_name.'%');
        $showtime_start_time&&$showtime_end_time&&$refund_list->whereBetween('session_datetime',[$showtime_start_time,$showtime_end_time]);
        $start_date_time&&$end_date_time&&$refund_list->whereBetween('date_time',[$start_date_time,$end_date_time]);
        $data = $refund_list->where(['operation'=>4,'cinema_code'=>$cinema_code])->paginate(15);
        return success($data,'查询成功');

    }






}
